
package com.xcx.services.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.xcx.common.services.common.FastDFSService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * fdfs服务类
 *
 * @author yangjun
 * @date 2018年7月12日 上午11:13:52
 */
@Service(interfaceClass = FastDFSService.class)
public class FastDFSServiceImpl implements FastDFSService {

    @Autowired
    private FastFileStorageClient storageClient;


    /**
     * 上传文件
     *
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    @Override
    public String uploadFile(MultipartFile file) {
        StorePath storePath;
        try {
            File file1 = new File("/opt");
            storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        } catch (Exception e) {
            return null;
        }
        return storePath.getFullPath();
    }

    /**
     * 将一段字符串生成一个文件上传
     *
     * @param content 文件内容
     * @return
     */
    @Override
    public String uploadFile(String content) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream, buff.length, null, null);

        return storePath.getFullPath();
    }

    /**
     * 删除文件
     *
     * @param fileUrl
     */
    @Override
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
        }
    }
}
 